﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.IO;

using System.Threading;
using System.Resources;
using System.Globalization;
using TrainingCenterSystem;
using TrainingCenterSystem.VocabularyManagement;
using TrainingCenterSystem.VocabularyManagement.Exceptions;

namespace TrainingCenterWinClient.Forms
{
    public partial class CollectionForm : Form
    {
        #region private members
        private TrainingCenter _trainingCenter;

        private ResourceManager _resMgr;

        private CollectionHandler _collectionHandler;

        private DataGridViewCell previousCell = null;
        #endregion 

        #region constructor(s)
        public CollectionForm(TrainingCenter trainingCenter, CollectionHandler collHandler)
        {
            _trainingCenter = trainingCenter;
            _collectionHandler=collHandler;
            
            InitializeComponent();
            this.initForm();
        }
        #endregion

        #region language-related methods
        private void UpdateLanguage(string langID)
        {
            try
            {
                // Set Language
                Thread.CurrentThread.CurrentUICulture = new CultureInfo(langID);

                // Init ResourceManager
                _resMgr =
                    new ResourceManager("TrainingCenterWinClient.ReStrings",
                    typeof(CollectionForm).Assembly);

                // assign localized strings to UI
                this.lblCurrentCollection.Text = _resMgr.GetString("CollectionForm_lblCurrentCollection");

                this.grpCollection.Text = _resMgr.GetString("CollectionForm_grpCollection");
                this.lblCollectionAccess.Text = _resMgr.GetString("CollectionForm_lblCollectionAccess");
                this.lblCollectionName.Text = _resMgr.GetString("CollectionForm_lblCollectionName");
                this.lblCollectionCreator.Text = _resMgr.GetString("CollectionForm_lblCollectionCreator");
                this.lblCollectionDescription.Text = _resMgr.GetString("CollectionForm_lblCollectionDescription");
                this.btnCreateCollection.Text = _resMgr.GetString("CollectionForm_btnCreateCollection");
                this.btnSaveCollection.Text = _resMgr.GetString("Command_Save");
                this.btnReadCollection.Text = _resMgr.GetString("CollectionForm_btnReadCollection");


                this.grpContext.Text = _resMgr.GetString("CollectionForm_grpContext");
                this.lblExistingContexts.Text = _resMgr.GetString("CollectionForm_lblExistingContext");
                this.lblNewContext.Text = _resMgr.GetString("CollectionForm_lblNewContext");
                this.lblWordType.Text = _resMgr.GetString("CollectionForm_lblWordType");
                this.btnAddOrUpdateContext.Text = _resMgr.GetString("CollectionForm_btnAddOrUpdateContext_Add");
                this.btnDeleteContext.Text = _resMgr.GetString("CollectionForm_btnDeleteContext");
                this.btnRenameContext.Text = _resMgr.GetString("CollectionForm_btnRenameContext");              
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion

        #region context-related methods
        private void initContextGroup()
        {
            if (_collectionHandler.CurrentCollections.Count == 0)
                this.grpContext.Enabled = false;
            else
            {
                this.grpContext.Enabled = true;
            }
        }

        private void updateContextGroup(bool active)
        {
            if (active)
            {
                this.grpContext.Enabled = true;
                this.cmbAvailableContexts.Items.Clear();
                for (int i = 0; i < _collectionHandler.CurrentCollections[_collectionHandler.CurrentIndex].Contexts.Count; i++)
                    this.cmbAvailableContexts.Items.Add(((VocabularyContext)_collectionHandler.CurrentCollections[_collectionHandler.CurrentIndex].Contexts[i]).ContextName);
                this.cmbAvailableContexts.SelectedIndex = 0;
            }
            else
            {
                this.grpContext.Enabled = false;
            }
        }

        private void setLabels()
        {
            Point p = new Point(this.lblExistingContexts.Location.X + this.lblExistingContexts.Size.Width + 5, this.lblExistingContexts.Location.Y);
            this.cmbAvailableContexts.Location = p;
        }

        private void cmbAvailableContexts_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.btnAddOrUpdateContext.Text = _resMgr.GetString("CollectionForm_btnAddOrUpdateContext_Add");
            this.txtContextName.Text = "";
        }

        private void txtContextName_TextChanged(object sender, EventArgs e)
        {

        }

        private void btnAddOrUpdateContext_Click(object sender, EventArgs e)
        {
            // retrieve the text
            string contextName = this.txtContextName.Text;

            if (contextName == "")
                return;

            // if adding a new context
            if (this.btnAddOrUpdateContext.Text == _resMgr.GetString("CollectionForm_btnAddOrUpdateContext_Add"))
            {
                if (!_collectionHandler.CurrentCollections[_collectionHandler.CurrentIndex].ContextExists(contextName))
                    _collectionHandler.CurrentCollections[_collectionHandler.CurrentIndex].addContext(contextName);
                //this.updateContextGroup(true);
            }

            // if updating a context
            else if (this.btnAddOrUpdateContext.Text == _resMgr.GetString("CollectionForm_btnAddOrUpdateContext_Update"))
            {
                int contextIndex = cmbAvailableContexts.SelectedIndex;
                contextName = this.txtContextName.Text;
                if ((contextIndex >= 0) && (contextName != ""))
                {
                    if (!_collectionHandler.CurrentCollections[_collectionHandler.CurrentIndex].ContextExists(contextIndex.ToString(),contextName))
                        _collectionHandler.CurrentCollections[_collectionHandler.CurrentIndex].RenameContext(contextIndex, contextName);
                }
                this.btnAddOrUpdateContext.Text = _resMgr.GetString("CollectionForm_btnAddOrUpdateContext_Add");
            }
            this.updateContextGroup(true);
        }

        private void btnRenameContext_Click(object sender, EventArgs e)
        {
            if (this.cmbAvailableContexts.SelectedIndex > 0)
            {
                string contextName = this.cmbAvailableContexts.SelectedItem.ToString(); ;
                this.txtContextName.Text = contextName;
                this.btnAddOrUpdateContext.Text = _resMgr.GetString("CollectionForm_btnAddOrUpdateContext_Update");
            }
        }        
        #endregion

        #region collection-related methods
        private void initCollectionComboBox()
        {
            if (_collectionHandler.CurrentCollections.Count == 0)
            {
                this.cmbLoadedCollections.Items.Add("None");
                this.cmbLoadedCollections.SelectedIndex = 0;
            }
            else
                this.updateCollectionComboBox(true);
        }

        private void initCollectionGroup()
        {
            this.txtCollectionCreator.Text = _trainingCenter.CurrentUser.Username;
            this.cmbCollectionAccess.Items.Add(_resMgr.GetString("AccessType_private"));
            this.cmbCollectionAccess.Items.Add(_resMgr.GetString("AccessType_readonly"));
            this.cmbCollectionAccess.Items.Add(_resMgr.GetString("AccessType_readwrite"));
            this.cmbCollectionAccess.SelectedIndex = 0;
        }

        private void updateCollectionComboBox(bool active)
        {
            // add collections to the combo box
            this.cmbLoadedCollections.Items.Clear();
            this.cmbLoadedCollections.Items.Add("None");
            for (int i = 0; i < _collectionHandler.CurrentCollections.Count; i++)
                this.cmbLoadedCollections.Items.Add(_collectionHandler.CurrentCollections[i].CollectionName);
            // if no collections are open
            if (this.cmbLoadedCollections.Items.Count == 1)
                this.cmbLoadedCollections.SelectedIndex = 0;
            else
                this.cmbLoadedCollections.SelectedIndex = 1;
        }

        private void updateCollectionGroup()
        {
        }

        private void btnCreateCollection_Click(object sender, EventArgs e)
        {
            // retrieve the attributes
            string collName = this.txtCollectionName.Text;
            string collCreator = this.txtCollectionCreator.Text;
            string collDescription = this.txtCollectionDescription.Text;

            // 1. check if something is missing
            if ((collCreator.Length == 0) ||
                (this.cmbCollectionAccess.SelectedIndex < 0) ||
                (collName.Length == 0))
                return;
            else // if everything is filled in
            {
                CollectionAccess collAccess = CollectionAccess.Private;
                if (this.cmbCollectionAccess.SelectedIndex == 1)
                    collAccess = CollectionAccess.ReadOnly;
                else if (this.cmbCollectionAccess.SelectedIndex == 2)
                    collAccess = CollectionAccess.ReadWrite;
                // 2. create collection
                _collectionHandler.CreateCollection(collName, _trainingCenter.CurrentUser, collAccess, collDescription);
                _collectionHandler.CurrentCollections[0].addContext(_resMgr.GetString("Collection_undefinedContext"));

                if (this.saveFile())
                {
                    this.updateContextGroup(true);
                    this.updateCollectionComboBox(true);
                    this.updateWordTypeComboBox(true);
                    this.gridVocabulary.AutoGenerateColumns = true;
                }
                else
                    _collectionHandler.RemoveCurrentCollection();
                
                //3. update context group and combo boxes
                
                //4. save the file
                
            }


        }

        private void cmbLoadedCollections_KeyDown(object sender, KeyEventArgs e)
        {
            this.cmbLoadedCollections.SelectedIndex = 0;
            e.Handled = true;
        }

        private void cmbLoadedCollections_SelectedIndexChanged(object sender, EventArgs e)
        {
            
            // if no collection is selected
            if (this.cmbLoadedCollections.SelectedIndex == 0)
            {
                this.updateContextGroup(false);
                this.updateVocabularyGrid(false);
                this.updateWordTypeComboBox(false);
            }
            else
            {
                _collectionHandler.SwitchCollection(this.cmbLoadedCollections.SelectedIndex - 1);
                this.updateContextGroup(true);
                this.updateWordTypeComboBox(true);
                this.updateVocabularyGrid(true);
            }
        }
        #endregion

        #region datagrid-related methods
        private void updateVocabularyGrid(bool active)
        {            
            // retrieve the selected word type
            if (this.cmbWordType.SelectedItem == null)
                this.cmbWordType.SelectedIndex = 1;
            string selectedWord = this.cmbWordType.SelectedItem.ToString();

            // bind the grid to the corresponding data source
            if (active)
            {
                this.gridVocabulary.Enabled = true;
                if (selectedWord == _resMgr.GetString("GenericWord"))
                {
                    this.gridVocabulary.DataSource = null;
                    this.gridVocabulary.DataSource = _collectionHandler.CurrentCollections[_collectionHandler.CurrentIndex].GetGenerics();
                }
                else if (selectedWord == _resMgr.GetString("Verb"))
                {
                    this.gridVocabulary.DataSource = _collectionHandler.CurrentCollections[_collectionHandler.CurrentIndex].GetVerbs();

                }
                else if (selectedWord == _resMgr.GetString("Noun"))
                {
                    this.gridVocabulary.DataSource = _collectionHandler.CurrentCollections[_collectionHandler.CurrentIndex].GetNouns();
                }
                else if (selectedWord == _resMgr.GetString("Adjective"))
                {
                    this.gridVocabulary.DataSource = _collectionHandler.CurrentCollections[_collectionHandler.CurrentIndex].GetAdjectives();
                }

                this.updateGridColumns(selectedWord);
            }
            else
            {
                this.gridVocabulary.DataSource = null;
                this.gridVocabulary.Enabled = false;
            }
        }

        private void updateGridColumns(string selectedWord)
        {
            if (selectedWord == _resMgr.GetString("Verb"))
            {
                this.updateVerbHeaders();
            }
            else if (selectedWord == _resMgr.GetString("Noun"))
            {
                this.updateNounHeaders();
            }
            else if (selectedWord == _resMgr.GetString("Adjective"))
            {
                this.updateAdjectiveHeaders();
            }
            else if (selectedWord == _resMgr.GetString("GenericWord"))
            {
                this.updateGenericHeaders();
            }
        }

        private void updateVerbHeaders()
        {
            for (int i = 0; i < this.gridVocabulary.Columns.Count; i++)
            {
                if (this.gridVocabulary.Columns[i].Name == "BaseValue")
                {
                    this.gridVocabulary.Columns[i].HeaderText = _resMgr.GetString("VerbHeader_Infinitive");
                    this.gridVocabulary.Columns[i].DisplayIndex = 0;
                }
                else if (this.gridVocabulary.Columns[i].Name == "Translations")
                {
                    this.gridVocabulary.Columns[i].HeaderText = _resMgr.GetString("GenericHeader_Translations");
                    this.gridVocabulary.Columns[i].DisplayIndex = 1;
                }
                else if (this.gridVocabulary.Columns[i].Name == "PresentForm")
                {
                    this.gridVocabulary.Columns[i].HeaderText = _resMgr.GetString("VerbHeader_Present");
                    this.gridVocabulary.Columns[i].DisplayIndex = 2;
                }
                else if (this.gridVocabulary.Columns[i].Name == "ImperfectForm")
                {
                    this.gridVocabulary.Columns[i].HeaderText = _resMgr.GetString("VerbHeader_Imperfect");
                    this.gridVocabulary.Columns[i].DisplayIndex = 3;
                }
                else if (this.gridVocabulary.Columns[i].Name == "Supinum")
                {
                    this.gridVocabulary.Columns[i].HeaderText = _resMgr.GetString("VerbHeader_Supinum");
                    this.gridVocabulary.Columns[i].DisplayIndex = 4;
                }
                else if (this.gridVocabulary.Columns[i].Name == "ParticipPerfect")
                {
                    this.gridVocabulary.Columns[i].HeaderText = _resMgr.GetString("VerbHeader_PartPerfect");
                    this.gridVocabulary.Columns[i].DisplayIndex = 5;
                }
                else if (this.gridVocabulary.Columns[i].Name == "ContextName")
                {
                    this.gridVocabulary.Columns[i].HeaderText = _resMgr.GetString("GenericHeader_ContextName");
                    this.gridVocabulary.Columns[i].DisplayIndex = 8;
                }
                else if (this.gridVocabulary.Columns[i].Name == "CollectionName")
                {
                    this.gridVocabulary.Columns[i].HeaderText = _resMgr.GetString("GenericHeader_CollectionName");
                    this.gridVocabulary.Columns[i].DisplayIndex = 7;
                }
                else if (this.gridVocabulary.Columns[i].Name == "IsRegular")
                {
                    this.gridVocabulary.Columns[i].HeaderText = _resMgr.GetString("VerbHeader_IsRegular");
                    this.gridVocabulary.Columns[i].DisplayIndex = 6;
                }
            }           
        }

        private void updateNounHeaders()
        {
            for (int i = 0; i < this.gridVocabulary.Columns.Count; i++)
            {
                if (this.gridVocabulary.Columns[i].Name == "BaseValue")
                {
                    this.gridVocabulary.Columns[i].HeaderText = _resMgr.GetString("GenericHeader_BaseValue");
                    this.gridVocabulary.Columns[i].DisplayIndex = 0;
                }
                else if (this.gridVocabulary.Columns[i].Name == "Translations")
                {
                    this.gridVocabulary.Columns[i].HeaderText = _resMgr.GetString("GenericHeader_Translations");
                    this.gridVocabulary.Columns[i].DisplayIndex = 1;
                }
                else if (this.gridVocabulary.Columns[i].Name == "Article")
                {
                    this.gridVocabulary.Columns[i].HeaderText = _resMgr.GetString("NounHeader_Article");
                    this.gridVocabulary.Columns[i].DisplayIndex = 2;
                }
                else if (this.gridVocabulary.Columns[i].Name == "DefinedSingular")
                {
                    this.gridVocabulary.Columns[i].HeaderText = _resMgr.GetString("NounHeader_DefSing");
                    this.gridVocabulary.Columns[i].DisplayIndex = 3;
                }
                else if (this.gridVocabulary.Columns[i].Name == "UndefinedPlural")
                {
                    this.gridVocabulary.Columns[i].HeaderText = _resMgr.GetString("NounHeader_UndefPl");
                    this.gridVocabulary.Columns[i].DisplayIndex = 4;
                }
                else if (this.gridVocabulary.Columns[i].Name == "UndefinedSingular")
                {
                    this.gridVocabulary.Columns[i].HeaderText = _resMgr.GetString("NounHeader_UndefSing");
                    this.gridVocabulary.Columns[i].DisplayIndex = 5;
                }
                else if (this.gridVocabulary.Columns[i].Name == "DefinedPlural")
                {
                    this.gridVocabulary.Columns[i].HeaderText = _resMgr.GetString("NounHeader_DefPl");
                    this.gridVocabulary.Columns[i].DisplayIndex = 6;
                }                
                else if (this.gridVocabulary.Columns[i].Name == "CollectionName")
                {
                    this.gridVocabulary.Columns[i].HeaderText = _resMgr.GetString("GenericHeader_CollectionName");
                    this.gridVocabulary.Columns[i].DisplayIndex = 7;
                }
                else if (this.gridVocabulary.Columns[i].Name == "ContextName")
                {
                    this.gridVocabulary.Columns[i].HeaderText = _resMgr.GetString("GenericHeader_ContextName");
                    this.gridVocabulary.Columns[i].DisplayIndex = 8;
                }
            }
        }

        private void updateAdjectiveHeaders()
        {
            for (int i = 0; i < this.gridVocabulary.Columns.Count; i++)
            {
                if (this.gridVocabulary.Columns[i].Name == "BaseValue")
                {
                    this.gridVocabulary.Columns[i].HeaderText = _resMgr.GetString("GenericHeader_BaseValue");
                    this.gridVocabulary.Columns[i].DisplayIndex = 0;
                }
                else if (this.gridVocabulary.Columns[i].Name == "Translations")
                {
                    this.gridVocabulary.Columns[i].HeaderText = _resMgr.GetString("GenericHeader_Translations");
                    this.gridVocabulary.Columns[i].DisplayIndex = 1;
                }
                else if (this.gridVocabulary.Columns[i].Name == "Comparative")
                {
                    this.gridVocabulary.Columns[i].HeaderText = _resMgr.GetString("AdjectiveHeader_Comparative");
                    this.gridVocabulary.Columns[i].DisplayIndex = 2;
                }
                else if (this.gridVocabulary.Columns[i].Name == "Superlative")
                {
                    this.gridVocabulary.Columns[i].HeaderText = _resMgr.GetString("AdjectiveHeader_Superlative");
                    this.gridVocabulary.Columns[i].DisplayIndex = 3;
                }                
                else if (this.gridVocabulary.Columns[i].Name == "CollectionName")
                {
                    this.gridVocabulary.Columns[i].HeaderText = _resMgr.GetString("GenericHeader_CollectionName");
                    this.gridVocabulary.Columns[i].DisplayIndex = 4;
                }
                else if (this.gridVocabulary.Columns[i].Name == "ContextName")
                {
                    this.gridVocabulary.Columns[i].HeaderText = _resMgr.GetString("GenericHeader_ContextName");
                    this.gridVocabulary.Columns[i].DisplayIndex = 5;
                }
            }

        }

        private void updateGenericHeaders()
        {
            this.gridVocabulary.Columns[0].HeaderText = _resMgr.GetString("GenericHeader_BaseValue");
            this.gridVocabulary.Columns[1].HeaderText = _resMgr.GetString("GenericHeader_Translations");
            this.gridVocabulary.Columns[2].HeaderText = _resMgr.GetString("GenericHeader_CollectionName");
            this.gridVocabulary.Columns[3].HeaderText = _resMgr.GetString("GenericHeader_ContextName");
        }

        private void gridVocabulary_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            // retrieve the current collection.
            VocabularyCollection currentCollection = _collectionHandler.CurrentCollections[_collectionHandler.CurrentIndex];
            VocabularyContext currentContext=(VocabularyContext)currentCollection.Contexts[this.cmbAvailableContexts.SelectedIndex];

            // check the access
            if ((currentCollection.CollectionAccess != CollectionAccess.ReadWrite)
                && (_trainingCenter.CurrentUser.Username != currentCollection.CollectionUser.Username))
            {
                MessageBox.Show(_resMgr.GetString("ReadingError_Access"));
                return;
            }


            if (this.gridVocabulary.DataSource is List<Verb>)
            {
                Verb v = new Verb();
                v.SetCollection(currentCollection);
                v.SetContext(currentContext);
                _collectionHandler.GetCollection(_collectionHandler.CurrentIndex).AddWord(v);//.GetGenerics().Add(new GenericWord());
                this.gridVocabulary.DataSource = _collectionHandler.GetCollection(_collectionHandler.CurrentIndex).GetVerbs();
            }
            else if (this.gridVocabulary.DataSource is List<Noun>)
            {
                Noun noun = new Noun();
                noun.SetCollection(currentCollection);
                noun.SetContext(currentContext);

                _collectionHandler.GetCollection(_collectionHandler.CurrentIndex).AddWord(noun);//.GetGenerics().Add(new GenericWord());
                this.gridVocabulary.DataSource = _collectionHandler.GetCollection(_collectionHandler.CurrentIndex).GetNouns();
            }
            else if (this.gridVocabulary.DataSource is List<Adjective>)
            {
                Adjective adj = new Adjective();
                adj.SetCollection(currentCollection);
                adj.SetContext(currentContext);

                _collectionHandler.GetCollection(_collectionHandler.CurrentIndex).AddWord(adj);//.GetGenerics().Add(new GenericWord());
                this.gridVocabulary.DataSource = _collectionHandler.GetCollection(_collectionHandler.CurrentIndex).GetAdjectives();
            }
            else if (this.gridVocabulary.DataSource is List<GenericWord>)
            {
                GenericWord word = new GenericWord();
                word.SetCollection(currentCollection);
                word.SetContext(currentContext);
                _collectionHandler.GetCollection(_collectionHandler.CurrentIndex).AddWord(word);//.GetGenerics().Add(new GenericWord());
                this.gridVocabulary.DataSource = _collectionHandler.GetCollection(_collectionHandler.CurrentIndex).GetGenerics();
            }
        }       
        #endregion       

        private void initForm()
        {
            // 1. init the language
            this.UpdateLanguage(_trainingCenter.CurrentLanguageID);

            // 5. init word type 
            this.initWordTypeComboBox();           

            // 2. init current collection
            this.initCollectionComboBox();
            
            // 3. init collection group box
            this.initCollectionGroup();

            // 4. init context group box
            this.initContextGroup();           

            // 6. set position for labels/textboxes etc.
            this.setLabels();
        }

        #region wordtype-related methods
        private void initWordTypeComboBox()
        {
            this.cmbWordType.Items.Add(_resMgr.GetString("GenericWord"));
            this.cmbWordType.Items.Add(_resMgr.GetString("Verb"));
            this.cmbWordType.Items.Add(_resMgr.GetString("Noun"));
            this.cmbWordType.Items.Add(_resMgr.GetString("Adjective"));
            this.cmbWordType.Enabled = false;
            this.cmbWordType.SelectedIndex = 0;
            if (this.cmbLoadedCollections.SelectedIndex == 0)
                cmbWordType.Enabled = false;
            else
            {
                cmbWordType.Enabled = true;
            }
        }                    

        private void updateWordTypeComboBox(bool active)
        {
            if (active)
            {
                this.cmbWordType.Enabled = true;                
                this.updateVocabularyGrid(true);
                
            }
            else
                this.cmbWordType.Enabled = false;
        }

        private void cmbWordType_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.cmbWordType.Enabled)
            {
                this.updateVocabularyGrid(true);
            }
        }
        #endregion                  

        private void gridVocabulary_CellLeave(object sender, DataGridViewCellEventArgs e)
        {
            this.previousCell = this.gridVocabulary.CurrentCell;            
        }

        private void gridVocabulary_CurrentCellChanged(object sender, EventArgs e)
        {

            if ((this.previousCell!=null)&&
                ((this.previousCell.RowIndex>=0)&&(this.previousCell.ColumnIndex>=0)))
            {                
                GenericWord aWord = (GenericWord)this.previousCell.OwningRow.DataBoundItem;
                _collectionHandler.CurrentCollections[_collectionHandler.CurrentIndex].UpdateWord(aWord);
            }
        }

        private void gridVocabulary_KeyPress(object sender, KeyPressEventArgs e)
        {
            //((e.KeyChar==(Char)Keys.ControlKey)&&
            if (e.KeyChar==2)
            {
                Clipboard.SetText(this.gridVocabulary.CurrentCell.Value.ToString());
                string test = Clipboard.GetText();
            }
        }

        private void btnSaveCollection_Click(object sender, EventArgs e)
        {
            // make sure, that a collection is open
            if (_collectionHandler.CurrentCollections.Count == 0)
                return;

            if (this.cmbLoadedCollections.SelectedIndex == 0)
            {
                MessageBox.Show(_resMgr.GetString("ErrorMessage_NoCollection"));
                return;
            }

            this.saveFile();
        }

        private bool saveFile()
        {
            //1. init the save file dialog            
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.DefaultExt = "xml";
            saveFileDialog.Filter = "Xml File|*.xml";
            saveFileDialog.InitialDirectory = "../testfiles";
            DialogResult result = saveFileDialog.ShowDialog();
            if (result == DialogResult.Cancel)
                return false;

            //2. retrieve the current collection
            string filename = saveFileDialog.FileName;
            VocabularyCollection coll = _collectionHandler.CurrentCollections[_collectionHandler.CurrentIndex];
            coll.FileName = Path.GetFullPath(filename);
            //3. send it to the collection file writer
            CollectionFileWriter filewriter = new CollectionFileWriter(coll, filename);
            return true;
        }

        /// <summary>
        /// Initializes the open-file-dialog
        /// </summary>
        /// <returns>true, if a file was selected</returns>
        private string readCollection()
        {
            string initialDir="../testfiles";            
            this.openCollectionFileDialog.DefaultExt = "xml";            
            this.openCollectionFileDialog.Filter = "Xml File|*.xml";
            this.openCollectionFileDialog.InitialDirectory = initialDir;
            if (this.openCollectionFileDialog.ShowDialog() == DialogResult.OK)
                return this.openCollectionFileDialog.FileName;
            return null;
        }

        private void btnReadCollection_Click(object sender, EventArgs e)
        {

            string filename = null;
            filename = this.readCollection();
            if (filename!=null)
            {
                CollectionFileReader reader=null;                
                try
                {
                    reader = new CollectionFileReader(_trainingCenter, _resMgr.GetString("ReadingError_Internal"), _resMgr.GetString("ReadingError_Access"));
                    reader.Read(filename);
                    _collectionHandler.AddCollection(reader.Collection);

                    // update word type combo box
                    if (!this.cmbWordType.Enabled)
                        this.updateWordTypeComboBox(true);
                    // update collection combo box
                    this.updateCollectionComboBox(true);

                    // update datagrid
                    this.updateVocabularyGrid(true);

                    // update context group box
                    this.updateContextGroup(true);

                }
                catch (CollectionFileReadingException exc)
                {
                    MessageBox.Show(exc.Message);
                }
                finally
                {
                    reader.CloseReader();
                }
            }           
        }

        private void gridVocabulary_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void CollectionForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.cmbLoadedCollections.SelectedIndex = 0;
            this.cmbWordType.Enabled = false;
        }

        private void btnDeleteContext_Click(object sender, EventArgs e)
        {

        }
    }
}
